package com.lucy.viewer.vditor.provider;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.lang.Validator;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.lucy.viewer.constant.ViewerServiceEnum;
import com.lucy.viewer.event.FileEditedEvent;
import com.lucy.viewer.params.ViewerFile;
import com.lucy.viewer.service.ViewerFileService;
import com.lucy.viewer.service.ViewerService;
import com.lucy.viewer.vditor.params.MdEditParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @author kindear
 * 预览markdown 服务实现
 */
@Slf4j
@Service
public class VditorViewerServiceImpl implements ViewerService {

    @Value("${server.host}")
    String serverHost;

    @Autowired(required = true)
    ViewerFileService viewerFileService;

    @Resource
    ApplicationContext context;

    @Override
    public ViewerServiceEnum service() {
        return ViewerServiceEnum.VDITOR;
    }

    @Override
    public ModelAndView loadPreviewView(String documentKey, HttpServletResponse response) throws IOException {
        ViewerFile viewerFile = viewerFileService.getViewerFile(documentKey);
        // 获取文件类型
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("mdpreview");
        modelAndView.addObject("file",viewerFile);
        return modelAndView;
    }

    @Override
    public ModelAndView loadEditorView(String documentKey, HttpServletResponse response) throws IOException {
        ViewerFile viewerFile = viewerFileService.getViewerFile(documentKey);
        MdEditParams params = new MdEditParams();
        BeanUtil.copyProperties(viewerFile,params, CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        // 设置回调地址
        params.setBackUrl(callbackUrl());
        // 设置内容 -- 需要读取文件
        String reqUrl = serverHost + viewerFile.getUrl();
        //log.info("请求地址{}",reqUrl);
//        if (viewerFile.getStorage().equals("local")){
//            reqUrl = serverHost + viewerFile.getLocalUrl();
//        }
//        HttpResponse res = HttpRequest.get(reqUrl).execute();
        // 获取文件真实存储路径
        String filePath = viewerFile.getPath();
        // 如果文件路径为空 --> 第三方文件
        if (Validator.isEmpty(filePath)){
            // 从远程地址读取
            HttpResponse res = HttpRequest.get(reqUrl).execute();
            String content = res.body();
            params.setContent(content);
        }else {
            // 从文件读取
            String content = FileReader.create(new File(filePath)).readString();
            params.setContent(content);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("mdeditor");
        modelAndView.addObject("file",params);
        return modelAndView;
    }

    @Override
    public Object editorCallBack(Map<String, Object> map) {
        log.info("---markdown change callback---");
        // 获取文件key
        String key = map.get("fileKey").toString();
        // 获取文件内容
        String content = map.get("content").toString();
//        // 打印内容
//       // log.info(content);
//        // 获取文件
        ViewerFile viewerFile = viewerFileService.getViewerFile(key);
//        // 获取文件路径
//        String filePath = viewerFile.getPath();
//        //写入
//        FileUtil.writeString(content,filePath, CharsetUtil.UTF_8);
        InputStream stream = IoUtil.toUtf8Stream(content);
        //log.info("写入成功");
        // 更新文件流
       // viewerFileService.updateViewerFile(FileUtil.getInputStream(new File(filePath)),key);
        viewerFileService.updateViewerFile(stream,key);
        // 发布文件编辑完成事件
        context.publishEvent(new FileEditedEvent(this,viewerFile));
        log.info("---markdown has modified---");
        return true;
    }

    private String callbackUrl() {
        return serverHost + "/viewer/vditor/callback";
    }

}
